//引入模块
let express = require('express');
let path = require('path');
let fs = require('fs');
let timeStamp = require('time-stamp');
let router = express.Router();
let formidable = require('formidable');
router.use(express.urlencoded({
    extended: true
}));
router.use('/images', express.static(path.join(__dirname, './images/')));

//渲染登录页面
router.get('/login', (req, res) => {
    let filePath = path.join(__dirname, '/views/login.html');
    res.sendFile(filePath);
});
router.get('/register', (req, res) => {
    let filePath = path.join(__dirname, '/views/register.html');
    res.sendFile(filePath);

});
//是否能注册成功
router.post('/doregister', (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    //进行判空
    if (username == '' || password == '') {
        res.send('请输入正确的用户名或密码');
        return;
    };
    //读取json文件
    let data = fs.readFileSync('./persons.json', 'utf-8');
    //把字符串转为数组
    let arr = JSON.parse(data);

    let index = arr.findIndex((item) =>
        item.username == username && item.password == password
    );

    //设置临时文件夹
    let form = formidable({
        uploadDir: path.join(__dirname, './onloads/')
    });

    //解析数据
    form.parse(req, (err, val, files) => {
        if (err) {
            res.send('上传错误');
        };
        // 把文件从临时目录移动到最终目录（renameSync 可以对整个路径进行重命名）
        //旧路径
        let oldpath = files.submit.filepath;
        //新文件夹
        let newDir = path.join(__dirname, './images/');
        //新文件夹名字
        let newName = files.submit.originalFilename;
        //新路径
        let newpath = path.join(newDir, newName);
        //重命名
        fs.renameSync(oldpath, newpath);
    });

    //获取当前时间
    let time = timeStamp('YYYY年MM月DD日 HH:mm:ss');
    //获取地址
    let url = path.join(__dirname, './images/OIP-C.jpg');
    let obj = {
        username,
        password,
        time,
        url
    };
    if (index == -1) {
        arr.push(obj);
        fs.writeFileSync("./persons.json", JSON.stringify(arr));
        res.send("注册成功");
    } else {
        res.send("用户名已注册");
    };
});
router.post('/dologin', (req, res) => {
    let username = req.body.username;
    let password = req.body.password;
    //进行判空
    if (username == '' || password == '') {
        res.send('用户名或密码不能为空');
        return;
    };
    //读取json文件
    let data = fs.readFileSync('./persons.json', 'utf-8');
    //把字符串转为数组
    let arr = JSON.parse(data);

    let index = arr.findIndex((item) =>
        item.username == username && item.password == password
    );

    console.log(index);
    if (index == -1) {
        res.send("请先注册账户");
    } else {
        res.send("登录成功");
    };
});
//暴露模块
module.exports = router;